package com.tao.picture.ui.girl.viewmodel

import android.app.Application
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.tao.BaseViewModel
import com.tao.data.Resource
import com.tao.di.getTaskManager
import com.tao.net.download.download
import com.tao.net.request
import com.tao.picture.ui.girl.data.entity.Girl
import com.tao.picture.ui.girl.data.repository.ImageRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class GirlsViewModel @Inject constructor(
    private val repository: ImageRepository,
    application: Application
) : BaseViewModel(application) {

    val girls: MutableLiveData<Resource<List<Girl>>> = MutableLiveData()
    val img: MutableLiveData<Resource<Uri>> = MutableLiveData()

    /**
     * 获取图片
     */
    fun getImage() {
        request(repository.getImages(), girls)
    }

    /**
     * 保存到db
     */
    fun saveImage(girls: List<Girl>) {
        viewModelScope.launch {
            // 切换io
            withContext(Dispatchers.IO) {
                repository.saveImages(girls)
            }
        }
    }

    fun saveImage(girl: Girl) {
        viewModelScope.launch {
            // 切换io
            withContext(Dispatchers.IO) {
                // 流是冷的，如果不collect,将不会执行
                repository.saveImage(girl).collect()
            }
        }
    }

    /**
     * 下载文件
     */
    fun download() {
        download("https://img2.baidu.com/it/u=2102736929,2417598652&fm=26&fmt=auto&gp=0.jpg", img)
    }

    fun downloadImg() {
        download("http://gank.io/images/7fa98787d009465a9d196fbff6b0a5d7", img, ".jpg")
    }

    /**
     * 取消下载
     */
    fun cancel() {
        getTaskManager().cancel("https://img2.baidu.com/it/u=2102736929,2417598652&fm=26&fmt=auto&gp=0.jpg")
    }

}